package com.dminvoicemanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DM_InvoiceSalesOrder extends Activity {
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String TEMP_USER = "invtempuser";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";
	private SQLiteDatabase mydb;

	final private static int DIALOG_CANCEL_INVOICE = 1;
	final private static int DIALOG_UNDO_INVOICE = 2;
	final private static int DIALOG_PRINT_INVOICE = 3;
	final private static int DIALOG_SAVE_INVOICE = 4;
	final private static int DIALOG_SELECT_CUSTOMER = 5;

	AlertDialog InvoiceHeaderAlert = null;
	Dialog invoiceListDialog;
	String TagId;
	int ListInvTag;
	EditText etdminvdate, etdminvcustomer, etdminvremarks, etdminvcusdis,
			etdminvdiscount;
	Button INVSelectCustomer, INVSelectItems, INVSave, INVPrint, INVCancel,
			INVUndo, etdminvno;
	LinearLayout ListViewShowCustomers, ListViewInvHeaderButton,
			ListViewInvHeaderDetails, ListViewselectinvoices;
	String match = "5";
	String invoiceSerial, InvoiceCustomerCode;
	String PrintTotalDiscountValue, PrintDiscountedInvValueItems,
			PrintTotCustomerInvDiscount;
	String invcuscode, invcusname, invcusdiscount, currentInvoiceTempRefCode,
			invheadcode, currentSerial, currentPreInvoiceCode;
	EditText marketretval, invoicetotval, invoicedisval;
	double InvDiscountValueItems = 0.0, InvValueItems = 0.0,
			InvValueItemsReturned = 0.0, InvDiscountValueCustomer = 0.0,
			TotCustomerInvDiscount = 0.0, TotalDiscountValue = 0.0,
			DiscountedInvValueItems = 0.0;
	String activeInvoiceCode = "1", currentUserTemp, currentUserPrefix,
			refNoSummaryInvoice;

	String RepInvCode, TransTypePrefix, AgentPrefixType, LatestInvNumber,
			LatestInvState, ActiveInvoice;
	int ButtonTag;
	DM_Invoice_list_dialog InvoiceListDialog;

	// ============Cancel Invoice===================
	public void btnCancelInvoice(View view) {
		if (etdminvno.length() != 0) {
			try {
				ButtonTag = 3;
				showDialog(DIALOG_CANCEL_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			ShowInvoiceList();
		}

	}

	// Undo Invoice Handling
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnCancelInvoiceAccept(View view) {
		// synchdata();

		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			latestInvoiceRecord();
			SaveMainInvoice();

		}
		updateInvoiceCancelState();
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();

	}

	// ==============Undo Invoice====================
	public void btnUndoInvoice(View view) {
		if (etdminvno.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	// Undo Invoice Handling
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			if(etdminvno.length() != 0){
				latestInvoiceRecord();
				updateInvoiceUndoState();
				clearInvoiceUndoFields();
				InvoiceHeaderAlert.dismiss();
			}
		
		}
		else if(ListInvTag == 99){
			Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
		}
		/*if (etdminvno.length() != 0) {
		
		}*/
		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAcceptExit(View view) {
		// synchdata();
		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			if(etdminvno.length() != 0){
			latestInvoiceRecord();
			updateInvoiceUndoState();
			clearInvoiceUndoFields();
			InvoiceHeaderAlert.dismiss();
			Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
			}
		}
	
			Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
		
		/*if (etdminvno.length() != 0) {
			
		}*/
		InvoiceHeaderAlert.dismiss();
	}

	private void clearInvoiceUndoFields() {
		// TODO Auto-generated method stub
		etdminvno.setText("");
		etdminvdate.setText(getCurrentTimeString().toString());
		etdminvcustomer.setText("");
		etdminvremarks.setText("");
		etdminvcusdis.setText("");
		etdminvdiscount.setText("");
		marketretval.setText("");
		invoicedisval.setText("");
		invoicetotval.setText("");
	}

	// ------------------List Invoice Dialog Dissmis-----------------
	public void btnClickDialogDissmiss(View view) {
		invoiceListDialog.dismiss();
	}

	// ------------------Print Invoice-----------------
	public void btnPrintInvoice(View view) {
		if (etdminvno.length() != 0) {
			try {
				showDialog(DIALOG_PRINT_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceSalesOrder.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT INVOICE");
			// Setting Dialog Message
			alertDialog.setMessage("Select Valid Invoice");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			return;
		}
	}

	// Undo Invoice Handling
	public void btnPrintInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnPrintInvoiceAccept(View view) {
		// Toast.makeText(getApplicationContext(), "Print Invoice Fail",
		// 1).show();
		InvoiceHeaderAlert.dismiss();
		/*
		 * Intent myIntent = new Intent(view.getContext(),
		 * DM_InvoiceMenu.class); startActivityForResult(myIntent, 0);
		 */
	}

	// ================================Save
	// Invoice=======================================

	// Save invoice details and invoice header details to activate invoice
	public void btnSaveInvoice(View view) {
		ButtonTag = 2;
		SaveMainInvoice();
	}

	public void btnSaveInvoiceAccept(View view) {
		if (etdminvno.length() != 0) {
			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			InvoiceHeaderAlert.dismiss();
			finish();

		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceSalesOrder.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVOICE ERROR");
			// Setting Dialog Message
			alertDialog.setMessage("Invoice Not Found");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			return;
		}

	}

	// ------------------Select Customer Invoice-----------------
	public void btnSelectCustomerAccept(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	// Back to Invoice header without selecting Customer
	public void btnCusListBack(View view) {
		ListViewShowCustomers.setVisibility(view.GONE);
		ListViewselectinvoices.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);
	}

	private void SaveMainInvoice() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues addnewInvoiceHeader = new ContentValues();
			addnewInvoiceHeader.put("RefNo", etdminvno.getText().toString());
			addnewInvoiceHeader.put("RefNo1", etdminvno.getText().toString());
			addnewInvoiceHeader.put("InvType", "1");
			addnewInvoiceHeader
					.put("TxnDate", etdminvdate.getText().toString());
			addnewInvoiceHeader.put("ManuRef", "");
			addnewInvoiceHeader.put("DealCode", "D001");
			addnewInvoiceHeader.put("RepCode", "SR001");
			addnewInvoiceHeader.put("AreaCode", "T001");
			addnewInvoiceHeader.put("RouteCode", "RUT001");
			addnewInvoiceHeader.put("DebCode", InvoiceCustomerCode);
			addnewInvoiceHeader.put("LocCode", "LV001");
			addnewInvoiceHeader.put("Remarks", etdminvremarks.getText()
					.toString());
			addnewInvoiceHeader.put("CostCode", "000");
			addnewInvoiceHeader.put("CurCode", "LKR");
			addnewInvoiceHeader.put("CurRate", "1.0000");
			addnewInvoiceHeader.put("TxnType", "22");
			addnewInvoiceHeader.put("InvAmt", invoicetotval.getText()
					.toString());
			if (etdminvdiscount.length() != 0) {
				addnewInvoiceHeader.put("OutDis", etdminvdiscount.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("OutDis", "0.00");
			}

			if (invoicedisval.length() != 0) {
				addnewInvoiceHeader.put("InvDis", invoicedisval.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("InvDis", "0.00");
			}
			if (marketretval.length() != 0) {
				addnewInvoiceHeader.put("TotMkrAmt", marketretval.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("TotMkrAmt", "0.00");
			}

			addnewInvoiceHeader.put("UnOvAmt", "0.00");
			if (invoicedisval.length() != 0) {
				addnewInvoiceHeader.put("TotalDis", invoicedisval.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("TotalDis", "0.00");
			}
			addnewInvoiceHeader.put("TotalAmt", invoicetotval.getText()
					.toString());
			addnewInvoiceHeader.put("AddUser", "DSPL");
			addnewInvoiceHeader.put("AddDateInvHead", getCurrentTimeString()
					.toString());
			addnewInvoiceHeader.put("AddMach", "PUBLISHER # Administrator");
			addnewInvoiceHeader.put("prtcopy", "0");
			addnewInvoiceHeader.put("RecordId", "1");
			addnewInvoiceHeader.put("timestamp_column", getCurrentTimeString()
					.toString());

			invheadcode = etdminvno.getText().toString();
			String[] accountdetail = invheadcode.split("/");
			String invSerialCode = accountdetail[0]; // invSerialCode
			String invSerialNo = accountdetail[1]; // invSerialNo
			Integer i = new Integer(invSerialNo);
			int Serialnum = i.intValue();
			currentSerial = Integer.toString(Serialnum);

			addnewInvoiceHeader.put("refInvoiceHeaderNo", currentSerial);
			addnewInvoiceHeader.put("refInvoiceHeaderCode", etdminvno.getText()
					.toString());

			mydb.insert(INV_HEADER, null, addnewInvoiceHeader);
			invoiceTransType();
			agentPrefix();
			latestInvoiceRecord();

			updateInvoiceCurrentState();
			if (ButtonTag == 2) {
				try {
					showDialog(DIALOG_SAVE_INVOICE);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			addNewInvoice();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();

	}

	// Update current invoice state
	private void updateInvoiceCurrentState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecup = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"tempRepInvSerial='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdateInvHead = new ContentValues();
						valueupdateInvHead.put("activeInvCusDiscountValue", etdminvdiscount.getText().toString());
						valueupdateInvHead.put("invoiceComplete", "2");// Invoice
																		// Save
																		// Complete
						valueupdateInvHead.put("activeInvoice", "0");
						valueupdateInvHead.put("invlateststate", "0");
						valueupdateInvHead.put("invoiceRef", etdminvno
								.getText().toString());

						mydb.update(TEMP_REP_INVOICESUMERY, valueupdateInvHead,
								"tempRepInvSerial=" + currentSerial, null);

					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecup.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
	}

	// Update current invoice Cancel state
	private void updateInvoiceCancelState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecup = mydb.query(TEMP_REP_INVOICESUMERY, columsup,
					"tempRepInvSerial='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdateInvHead = new ContentValues();

						valueupdateInvHead.put("invoiceComplete", "5");// Invoice
																		// Save
																		// Complete
						valueupdateInvHead.put("activeInvoice", "0");
						valueupdateInvHead.put("invlateststate", "0");
						mydb.update(TEMP_REP_INVOICESUMERY, valueupdateInvHead,
								"tempRepInvSerial=" + currentSerial, null);
					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecup.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
	}

	// Update current invoice Undo state
	private void updateInvoiceUndoState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecupdate = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecupdate = mydb.query(TEMP_REP_INVOICESUMERY,
					columsup, "tempRepInvSerial='" + currentSerial + "'", null,
					null, null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecupdate != null) {
				if (selectLastinvrecupdate.getCount() > 0) {
					while (selectLastinvrecupdate.moveToNext()) {
						ContentValues valueupdateInvHeadUpdate = new ContentValues();
						valueupdateInvHeadUpdate.put("invoiceComplete", "0");// Invoice
																				// Save
																				// Complete
						valueupdateInvHeadUpdate.put("activeInvoice", "1");
						valueupdateInvHeadUpdate.put("activeInvoiceValue", "0");
						valueupdateInvHeadUpdate.put("activeInvItemDiscount",
								"0");
						valueupdateInvHeadUpdate.put("activeInvCusDiscount",
								"0");
						valueupdateInvHeadUpdate.put(
								"activeInvCusDiscountValue", "0");
						valueupdateInvHeadUpdate
								.put("InvoiceCustomerCode", "0");
						valueupdateInvHeadUpdate
								.put("InvoiceCustomerName", "0");
						valueupdateInvHeadUpdate.put("InvoiceSynchState", "0");
						valueupdateInvHeadUpdate.put("recordDate",
								getCurrentTimeString());
						valueupdateInvHeadUpdate.put("recordSynchDate", "0");
						if (ListInvTag != 99) {
							valueupdateInvHeadUpdate.put("invlateststate", "9");
						} else {
							valueupdateInvHeadUpdate.put("invlateststate", "0");
						}
						valueupdateInvHeadUpdate.put(
								"activeInvoiceReturnValue", "0");
						valueupdateInvHeadUpdate.put("activeInvoiceRemarks",
								"enter remarks");
						valueupdateInvHeadUpdate.put("invoiceNoOfItems", "0");

						mydb.update(TEMP_REP_INVOICESUMERY,
								valueupdateInvHeadUpdate, "tempRepInvSerial="
										+ currentSerial, null);

					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecupdate.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
		// Delete records from invoice items details
		deleteUndoInvoiceItems();
	}

	private void deleteUndoInvoiceItems() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor undoinvitemslist = null;
		String columsup[] = { "refInvoiceDetNo" };
		try {
			undoinvitemslist = mydb.query(INV_DETAILS, columsup,
					"refInvoiceDetNo='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		if (undoinvitemslist != null) {
			if (undoinvitemslist.getCount() > 0) {
				while (undoinvitemslist.moveToNext()) {
					mydb.delete(INV_DETAILS, "refInvoiceDetNo ='"
							+ currentSerial + "'", null);
				}
			}
		}
		undoinvitemslist.close();
		mydb.close();
	}

	// Once complete current invoice will generate new invoice
	private void addNewInvoice() {
		// TODO Auto-generated method stub
		int preInvoiceNo = Integer.parseInt(currentSerial);
		int newInvoiceNo = preInvoiceNo + 1;
		LatestInvNumber = String.valueOf(newInvoiceNo);
		ActiveInvoice = "1";
		RepInvCode = TransTypePrefix.trim() + AgentPrefixType.trim()
				+ currentUserPrefix;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			ContentValues saveTempuserinvoice = new ContentValues();
			saveTempuserinvoice.put("repusername", currentUserTemp);
			saveTempuserinvoice.put("repprefix", currentUserPrefix);
			saveTempuserinvoice.put("tempRepInvNoCode", RepInvCode);
			saveTempuserinvoice.put("tempRepInvSerial", LatestInvNumber);
			saveTempuserinvoice.put("invoiceComplete", "0");
			saveTempuserinvoice.put("activeInvoice", ActiveInvoice);
			saveTempuserinvoice.put("activeInvoiceValue", "0");
			saveTempuserinvoice.put("activeInvItemDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscountValue", "0");
			saveTempuserinvoice.put("InvoiceCustomerCode", "0");
			saveTempuserinvoice.put("InvoiceCustomerName", "0");
			saveTempuserinvoice.put("InvoiceSynchState", "0");
			saveTempuserinvoice.put("recordDate", getCurrentTimeString());
			saveTempuserinvoice.put("recordSynchDate", "0");
			saveTempuserinvoice.put("invlateststate", "9");
			saveTempuserinvoice.put("activeInvoiceReturnValue", "0");
			saveTempuserinvoice.put("activeInvoiceRemarks", "enter remarks");
			saveTempuserinvoice.put("invoiceNoOfItems", "0");
			saveTempuserinvoice.put("invoiceRef", "0");

			mydb.insert(TEMP_REP_INVOICESUMERY, null, saveTempuserinvoice);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
	}

	protected void latestInvoiceRecord() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String[] resultserial = { "tempRepInvSerial" };
		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invlateststate='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {
				if (selectLastinvrec.moveToLast()) {
					currentSerial = selectLastinvrec.getString(4);
					LatestInvState = selectLastinvrec.getString(5); // If
																	// invoice
																	// complete
					if (LatestInvState.equals(2)) {
						// saveTempuserDeails();
					} else {
					}
					selectLastinvrec.close();
				}
			} else {
				LatestInvNumber = "1";
				LatestInvState = "0";
				ActiveInvoice = "1";
				addNewInvoice();
			}
		} else {
			LatestInvNumber = "1";
			LatestInvState = "0";
			ActiveInvoice = "1";
			addNewInvoice();
		}
		mydb.close();
	}

	protected void agentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					AgentPrefixType = selectAgentPreType.getString(18);
				}

			}
		}
		mydb.close();
	}

	protected void invoiceTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("SECINV")) {
						TransTypePrefix = cCharValue.trim();
					}

				}
			}
		}
		mydb.close();
	}

	// Print Account Description
	public void AddCustomerDetails(View view) {
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		String[] accountdetail = SetTransactionDesc.split("/");
		invcuscode = accountdetail[0]; // invcuscode
		invcusname = accountdetail[1]; // invcusname
		invcusdiscount = accountdetail[2]; // invcusdiscount

		etdminvcustomer.setText(invcusname);
		etdminvcusdis.setText(invcusdiscount);
		ListViewShowCustomers.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);
	}

	public void AddLocationItemsDetails(View view) {
		Button des = (Button) view;
		refNoSummaryInvoice = des.getText().toString();
		viewInvoiceSummary();
		ListInvTag = 99;
		ListViewselectinvoices.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);

	}

	private void viewInvoiceSummary() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowinvsum = null;
		try {
			allrowinvsum = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"invoiceRef='" + refNoSummaryInvoice + "'", null, null,
					null, null);
		} catch (Exception e) {
		}
		if (allrowinvsum != null) {
			if (allrowinvsum.getCount() > 0) {
				while (allrowinvsum.moveToNext()) {
					currentSerial = allrowinvsum.getString(4);
					Toast.makeText(getApplicationContext(),
							"currentSerial:" + currentSerial,
							Toast.LENGTH_SHORT).show();
					String recordDate = allrowinvsum.getString(14);
					String InvoiceCustomerName = allrowinvsum.getString(12);
					String activeInvCusDiscount = allrowinvsum.getString(9);
					String activeInvoiceReturnValue = allrowinvsum
							.getString(17);
					String activeInvItemDiscount = allrowinvsum.getString(8);
					String activeInvCusDiscountValue = allrowinvsum
							.getString(10);
					String activeInvoiceValue = allrowinvsum.getString(7);
					etdminvno.setText(refNoSummaryInvoice);
					etdminvdate.setText(recordDate);
					etdminvcustomer.setText(InvoiceCustomerName);
					etdminvremarks.setText("remark");
					etdminvcusdis.setText(activeInvCusDiscount);
					etdminvdiscount.setText(activeInvItemDiscount);
					marketretval.setText(activeInvoiceReturnValue);
					invoicedisval.setText(activeInvCusDiscountValue);
					invoicetotval.setText(activeInvoiceValue);

					INVSelectCustomer.setEnabled(false);
					INVSelectItems.setEnabled(false);
					// jana
				}
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_sales_order);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");
		currentuserTemp();
		populateCustomerList();

		etdminvno = (Button) findViewById(R.id.etdminvno);
		etdminvdate = (EditText) findViewById(R.id.etdminvdate);
		etdminvcustomer = (EditText) findViewById(R.id.etdminvcustomer);
		etdminvremarks = (EditText) findViewById(R.id.etdminvremarks);
		etdminvcusdis = (EditText) findViewById(R.id.etdminvcusdis);
		etdminvdiscount = (EditText) findViewById(R.id.etdminvdiscount);

		marketretval = (EditText) findViewById(R.id.marketretval);
		invoicedisval = (EditText) findViewById(R.id.invoicedisval);
		invoicetotval = (EditText) findViewById(R.id.invoicetotval);

		INVSelectCustomer = (Button) findViewById(R.id.btninvselectcustomer);
		INVSelectItems = (Button) findViewById(R.id.btninvdetails);
		INVSave = (Button) findViewById(R.id.account_saveButton);
		INVPrint = (Button) findViewById(R.id.account_printButton);
		INVCancel = (Button) findViewById(R.id.account_cancelButton);
		INVUndo = (Button) findViewById(R.id.account_undoButton);

		ListViewShowCustomers = (LinearLayout) findViewById(R.id.dminvoiceselectcus);
		ListViewInvHeaderButton = (LinearLayout) findViewById(R.id.invheaderbuttons);
		ListViewInvHeaderDetails = (LinearLayout) findViewById(R.id.dminvoiceheadersection);
		ListViewselectinvoices = (LinearLayout) findViewById(R.id.dminvoiceselectinvoices);
		etdminvdate.setText(getCurrentTimeString());

		// Button touchup Event handling
		etdminvno.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent motionevent) {
				int action = motionevent.getAction();
				if (action == MotionEvent.ACTION_DOWN) {
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "Button ACTION_DOWN", Toast.LENGTH_SHORT).show();
					 */
				} else if (action == MotionEvent.ACTION_UP) {
					ListViewselectinvoices.setVisibility(view.VISIBLE);
					ListViewInvHeaderButton.setVisibility(view.GONE);
					ListViewInvHeaderDetails.setVisibility(view.GONE);
					ShowInvoiceList();
					// jana
				}
				return false;

			}

		});

		if (TagId.equals(match)) {
			INVSave.setEnabled(true);
			INVPrint.setEnabled(true);
			INVCancel.setEnabled(true);
			INVUndo.setEnabled(true);
			viewInvoiceHeaderDetails();
		}
		INVSelectItems.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (etdminvcustomer.length() == 0 || etdminvdate.length() == 0) {
					try {
						showDialog(DIALOG_SELECT_CUSTOMER);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					return;
				} else {
					updateInvoiceSummery();
					Intent myIntent = new Intent(view.getContext(),
							DM_InvoiceDetails.class);
					myIntent.putExtra("TAGID", "4");
					startActivityForResult(myIntent, 0);
				}

			}

		});

		INVSelectCustomer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				ListViewShowCustomers.setVisibility(view.VISIBLE);
				ListViewInvHeaderButton.setVisibility(view.GONE);
				ListViewInvHeaderDetails.setVisibility(view.GONE);

			}

		});

	}

	protected void ShowInvoiceList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewInvoices);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.invListingViewNo,
				R.id.invListingViewSum };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			allrowtypedes = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invoiceComplete !='0'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String remprepinv_id = allrowtypedes.getString(0);
					String tempRepInvNoCode = allrowtypedes.getString(3);
					String tempRepInvSerial = allrowtypedes.getString(4);
					String invRefNo = allrowtypedes.getString(20);
					String columncusdet = remprepinv_id + "/"
							+ tempRepInvNoCode + "/" + tempRepInvSerial;
					String flagno = "00000";
					String PrintRefNo = tempRepInvNoCode + "/" + flagno
							+ tempRepInvSerial;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", PrintRefNo);
					maptrdes.put("colinvoice_2", invRefNo);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_pre_invoice_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(TEMP_USER, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);

				}
			}
		}
		latestInvoiceNumber();// Get current invoice temp
		// number(currentInvoiceTempNo)
	}

	private void viewInvoiceHeaderDetails() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor latestinvoicerow = null;
		try {
			latestinvoicerow = mydb.query(TEMP_REP_INVOICESUMERY, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (latestinvoicerow != null) {
			if (latestinvoicerow.getCount() > 0) {
				while (latestinvoicerow.moveToNext()) {
					String repusername = latestinvoicerow.getString(1);
					String repprefix = latestinvoicerow.getString(2);
					String tempRepInvNoCode = latestinvoicerow.getString(3);
					String tempRepInvSerial = latestinvoicerow.getString(4);
					String rinvoiceComplete = latestinvoicerow.getString(5);
					String activeInvoice = latestinvoicerow.getString(6);
					String activeInvoiceValue = latestinvoicerow.getString(7);
					InvValueItems = Double.parseDouble(activeInvoiceValue
							.trim());// Invoice Tot Val
					String activeInvItemDiscount = latestinvoicerow
							.getString(8);
					InvDiscountValueItems = Double
							.parseDouble(activeInvItemDiscount.trim());// Discount
																		// Value
																		// for
																		// Items
					String activeInvCusDiscount = latestinvoicerow.getString(9);
					InvDiscountValueCustomer = Double
							.parseDouble(activeInvCusDiscount);// Customer
																// Discout Rate
					String activeInvCusDiscountValue = latestinvoicerow
							.getString(10);
					InvoiceCustomerCode = latestinvoicerow.getString(11);
					String InvoiceCustomerName = latestinvoicerow.getString(12);
					String InvoiceSynchState = latestinvoicerow.getString(13);
					String recordDate = latestinvoicerow.getString(14);
					String recordSynchDate = latestinvoicerow.getString(15);
					String activeInvoiceReturnValue = latestinvoicerow
							.getString(17);

					// **********Calculations For Calculate Discount
					// Values**************
					TotCustomerInvDiscount = (InvValueItems * InvDiscountValueCustomer) / 100;
					TotCustomerInvDiscount = Math
							.round(TotCustomerInvDiscount * 100) / 100.0d;
					PrintTotCustomerInvDiscount = Double
							.toString(TotCustomerInvDiscount);
					TotalDiscountValue = (InvDiscountValueItems + TotCustomerInvDiscount);
					TotalDiscountValue = Math.round(TotalDiscountValue * 100) / 100.0d;
					PrintTotalDiscountValue = Double
							.toString(TotalDiscountValue);
					DiscountedInvValueItems = (InvValueItems - TotCustomerInvDiscount);
					DiscountedInvValueItems = Math
							.round(DiscountedInvValueItems * 100) / 100.0d;
					PrintDiscountedInvValueItems = Double
							.toString(DiscountedInvValueItems);
					// ********************************************************************

					try {
						if (tempRepInvSerial.length() == 1) {
							String newInvNumberStr = "00000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 2) {
							String newInvNumberStr = "0000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 3) {
							String newInvNumberStr = "000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 4) {
							String newInvNumberStr = "00" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 5) {
							String newInvNumberStr = "0" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else {
							String newInvNumberStr = tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						}
						etdminvno.setText(currentInvoiceTempRefCode);
						etdminvdate.setText(getCurrentTimeString());
						etdminvcustomer.setText(InvoiceCustomerName);
						etdminvremarks.setText("remarks");
						etdminvcusdis.setText(activeInvCusDiscount);
						etdminvdiscount.setText(PrintTotCustomerInvDiscount);

						invoicedisval.setText(PrintTotalDiscountValue); // Toal
																		// Discount
																		// For
																		// Invoice
						invoicetotval.setText(PrintDiscountedInvValueItems);
						marketretval.setText(activeInvoiceReturnValue);
					} catch (Exception e) {
						Toast.makeText(getApplicationContext(),
								"Error Occured..", Toast.LENGTH_SHORT).show();
					}
				}
			}
		}
		latestinvoicerow.close();
		mydb.close();
	}

	protected void updateInvoiceSummery() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };
		try {

			selectLastinvrecup = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invlateststate='9'", null, null, null,
					null);

		} catch (Exception e) {
		}
		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdate = new ContentValues();
						String LatestInvNumberStr = selectLastinvrecup
								.getString(0);

						valueupdate.put("InvoiceCustomerCode", invcuscode);// Add
																			// latest
																			// customer
						valueupdate.put("InvoiceCustomerName", invcusname);// Add
																			// latest
						// customer
						valueupdate.put("activeInvCusDiscount", invcusdiscount);// Add
																				// latest
						// customer
						mydb.update(TEMP_REP_INVOICESUMERY, valueupdate,
								"remprepinv_id ='" + LatestInvNumberStr + "'",
								null);
					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1 inv new", Toast.LENGTH_SHORT)
							.show();
				}
				selectLastinvrecup.close();
			}

			else {
				Toast.makeText(getApplicationContext(),
						"Error in update 2 inv new", Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
	}

	private void latestInvoiceNumber() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor latestinvoicerowdet = null;
		String columsLInv[] = { "activeInvoice" };

		try {
			latestinvoicerowdet = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invoiceComplete='1'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (latestinvoicerowdet != null) {
			if (latestinvoicerowdet.getCount() > 0) {

				while (latestinvoicerowdet.moveToNext()) {

					String repusername = latestinvoicerowdet.getString(1);
					invoiceSerial = latestinvoicerowdet.getString(4);
				}
			}
		} else {
			Toast.makeText(getApplicationContext(), "Enter New Invoice***",
					Toast.LENGTH_SHORT).show();
		}
		latestinvoicerowdet.close();
		mydb.close();
	}

	private void populateCustomerList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewcutommer);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoicecustommer, R.id.invcustomername };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			allrowtypedes = mydb.query(ITEM_DEBTOR, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String customercode = allrowtypedes.getString(1);
					String customername = allrowtypedes.getString(2);
					String customerdiscount = allrowtypedes.getString(10);
					String columncusdet = customercode + "/" + customername
							+ "/" + customerdiscount;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", columncusdet);
					maptrdes.put("coldes_2", customername);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_customer_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	private String getCurrentTimeString() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_CANCEL_INVOICE:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Cancel Current Invoice Details...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();

			break;

		case DIALOG_UNDO_INVOICE:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Undo Current Invoice Details...");
			dialogbuilderu.setView(dialogviewu);
			InvoiceHeaderAlert = dialogbuilderu.create();
			break;

		case DIALOG_PRINT_INVOICE:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_print_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			InvoiceHeaderAlert = dialogbuilderp.create();
			break;

		case DIALOG_SAVE_INVOICE:
			LayoutInflater inflaters = LayoutInflater.from(this);
			View dialogviews = inflaters.inflate(
					R.layout.dm_dialog_save_invoice, null);

			AlertDialog.Builder dialogbuilders = new AlertDialog.Builder(this);
			dialogbuilders.setTitle("Invoice Saved Successfully...");
			dialogbuilders.setView(dialogviews);
			InvoiceHeaderAlert = dialogbuilders.create();
			break;

		case DIALOG_SELECT_CUSTOMER:
			LayoutInflater inflatercus = LayoutInflater.from(this);
			View dialogviewcus = inflatercus.inflate(
					R.layout.dm_dialog_select_customer, null);

			AlertDialog.Builder dialogbuildercus = new AlertDialog.Builder(this);
			dialogbuildercus.setTitle("Please Select Customer...");
			dialogbuildercus.setView(dialogviewcus);
			InvoiceHeaderAlert = dialogbuildercus.create();
			break;
		}

		return InvoiceHeaderAlert;
	}

}
